
 <!DOCTYPE HTML>
<html >
<head>
  <meta charset="UTF-8">
  
    <title>jdbcTemplate实现HA | Typhoon&#39;s code space</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="typhoon">
    

    
    <meta name="description" content="在传统系统或网站架构中,一般都是使用单点,当然单点在应对并发访问量不是很大的场景下是能够应对自如的, 并且单机不存在服务延迟,分布式事务等问题,部署也比较简单。但是随着互联网的发展,传统的架构已经远远">
<meta name="keywords" content="jdbcTemplate高可用">
<meta property="og:type" content="article">
<meta property="og:title" content="jdbcTemplate实现HA">
<meta property="og:url" content="http://scorpioaeolus.oschina.io/2017/09/17/jdbcTemplate实现HA/index.html">
<meta property="og:site_name" content="Typhoon&#39;s code space">
<meta property="og:description" content="在传统系统或网站架构中,一般都是使用单点,当然单点在应对并发访问量不是很大的场景下是能够应对自如的, 并且单机不存在服务延迟,分布式事务等问题,部署也比较简单。但是随着互联网的发展,传统的架构已经远远">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/09/17/jdbcTemplate实现HA/1.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/09/17/jdbcTemplate实现HA/2.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/09/17/jdbcTemplate实现HA/3.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/09/17/jdbcTemplate实现HA/4.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/09/17/jdbcTemplate实现HA/5.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/09/17/jdbcTemplate实现HA/6.png">
<meta property="og:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/09/17/jdbcTemplate实现HA/7.png">
<meta property="og:updated_time" content="2017-09-17T14:09:54.814Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="jdbcTemplate实现HA">
<meta name="twitter:description" content="在传统系统或网站架构中,一般都是使用单点,当然单点在应对并发访问量不是很大的场景下是能够应对自如的, 并且单机不存在服务延迟,分布式事务等问题,部署也比较简单。但是随着互联网的发展,传统的架构已经远远">
<meta name="twitter:image" content="http://scorpioaeolus.oschina.io/typhoon/2017/09/17/jdbcTemplate实现HA/1.png">

    
    <link rel="alternative" href="/atom.xml" title="Typhoon&#39;s code space" type="application/atom+xml">
    
    
    <link rel="icon" href="/typhoon/img/java.png">
    
    
    <link rel="apple-touch-icon" href="/typhoon/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/typhoon/img/jacman.jpg">
    
    <link rel="stylesheet" href="/typhoon/css/style.css">
</head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/typhoon/"><img src="/typhoon/img/java.png" alt="Typhoon&#39;s code space" title="Typhoon&#39;s code space"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/typhoon/" title="Typhoon&#39;s code space">Typhoon&#39;s code space</a></h1>
				<h2 class="blog-motto"></h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/typhoon/">主页</a></li>
					
						<li><a href="/typhoon/archives">归档</a></li>
					
						<li><a href="/typhoon/about">关于</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:scorpioaeolus.oschina.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/typhoon/2017/09/17/jdbcTemplate实现HA/" title="jdbcTemplate实现HA" itemprop="url">jdbcTemplate实现HA</a>
  </h1>
  <p class="article-author">By
       
		<a href="/typhoon/about" title="typhoon" target="_blank" itemprop="author">typhoon</a>
		
  <p class="article-time">
    <time datetime="2017-09-17T14:00:25.000Z" itemprop="datePublished"> Published 2017-09-17</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#一、创建maven项目并添加最简依赖"><span class="toc-number">1.</span> <span class="toc-text">一、创建maven项目并添加最简依赖</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#二、添加配置文件"><span class="toc-number">2.</span> <span class="toc-text">二、添加配置文件</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#三、编写实现查询HA的相关类"><span class="toc-number">3.</span> <span class="toc-text">三、编写实现查询HA的相关类</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#四、添加HA相关配置"><span class="toc-number">4.</span> <span class="toc-text">四、添加HA相关配置</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#五、测试"><span class="toc-number">5.</span> <span class="toc-text">五、测试</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li></ol>
		
		</div>
		
		<pre><code>在传统系统或网站架构中,一般都是使用单点,当然单点在应对并发访问量不是很大的场景下是能够应对自如的,
并且单机不存在服务延迟,分布式事务等问题,部署也比较简单。但是随着互联网的发展,传统的架构已经远远
</code></pre><a id="more"></a>
<pre><code>满足不了庞大的并发访问量,并且单机所带来的问题也日益显著,比如:1)系统挂掉所有用户都无法访问  
2)当瞬时访问量比较大的时候单机部署的站点,单纯的通过硬件的扩充已经解决不了性能瓶颈问题;
现在比较流行的就是SOA或者微服务,归根结底其目的就是解决单机情况下的系统可用性,可靠性以及性能问题,
这里简单描述一下从请求接受层到数据库层的通用架构方案:
1.反向代理层:比较常用的就是nginx做反向代理和负载均衡
2.站点层:tomcat做集群
3.服务层:各种rpc框架都提供了负载均衡(dubbo)
4.数据库层:大多使用DB+cache方式,DB的话又分很多种主从复制方式(一主多从,双主以及其他数据库中间件实现的读写分离方案)


本篇文章对其他问题不做赘述,简单对读写分离中的多个从库实现负载均衡访问和提高查询高可用(基于JdbcTemplate实现),实现步骤如下
</code></pre><h5 id="一、创建maven项目并添加最简依赖"><a href="#一、创建maven项目并添加最简依赖" class="headerlink" title="一、创建maven项目并添加最简依赖"></a>一、创建maven项目并添加最简依赖</h5><ol>
<li>新建maven项目,项目结构如下图:</li>
</ol>
<img src="/typhoon/2017/09/17/jdbcTemplate实现HA/1.png" alt="result" title="result"> 
<ol>
<li>添加依赖<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div></pre></td><td class="code"><pre><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;junit&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;junit&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;4.11&lt;/version&gt;</div><div class="line">	&lt;scope&gt;test&lt;/scope&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- mysql connector --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;mysql&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;5.1.41&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- spring依赖 --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;org.springframework&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;4.3.7.RELEASE&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;org.springframework&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;spring-context&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;4.3.7.RELEASE&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;	</div><div class="line">&lt;!-- druid jdbcpool --&gt;	</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;com.alibaba&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;druid&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;1.1.2&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- fastjson --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;com.alibaba&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;fastjson&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;1.2.28&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- log4j --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">	&lt;groupId&gt;log4j&lt;/groupId&gt;</div><div class="line">	&lt;artifactId&gt;log4j&lt;/artifactId&gt;</div><div class="line">	&lt;version&gt;1.2.17&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div><div class="line">&lt;!-- commons --&gt;</div><div class="line">&lt;dependency&gt;</div><div class="line">    &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;</div><div class="line">    &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;</div><div class="line">    &lt;version&gt;3.1&lt;/version&gt;</div><div class="line">&lt;/dependency&gt;</div></pre></td></tr></table></figure>
</li>
</ol>
<h5 id="二、添加配置文件"><a href="#二、添加配置文件" class="headerlink" title="二、添加配置文件"></a>二、添加配置文件</h5><ol>
<li><p>添加jdbc属性配置(jdbc.properties)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">jdbc.trace=true</div><div class="line"># 写库</div><div class="line">jdbc.crmupdate.database=10.11.9.243:3306/test</div><div class="line">jdbc.crmupdate.user=crm</div><div class="line">jdbc.crmupdate.password=USszJ497whda</div><div class="line"></div><div class="line"># 读库1</div><div class="line">jdbc.crmquery1.database=10.11.9.243:3306/test</div><div class="line">jdbc.crmquery1.user=crm</div><div class="line">jdbc.crmquery1.password=USszJ497whda</div><div class="line"></div><div class="line"># 读库2</div><div class="line">jdbc.crmquery2.database=10.1.8.76:3306/test</div><div class="line">jdbc.crmquery2.user=root</div><div class="line">jdbc.crmquery2.password=root</div></pre></td></tr></table></figure>
</li>
<li><p>添加日志配置(log4j.properties)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line">### 设置###</div><div class="line">log4j.rootLogger = info,stdout,D,E</div><div class="line"></div><div class="line">### 输出信息到控制抬 ###</div><div class="line">log4j.appender.stdout = org.apache.log4j.ConsoleAppender</div><div class="line">log4j.appender.stdout.Target = System.out</div><div class="line">log4j.appender.stdout.layout = org.apache.log4j.PatternLayout</div><div class="line">log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d&#123;yyyy-MM-dd HH:mm:ss,SSS&#125; method:%l%n%m%n</div><div class="line"></div><div class="line">### 输出DEBUG 级别以上的日志文件设置 ###</div><div class="line">log4j.appender.D = org.apache.log4j.DailyRollingFileAppender</div><div class="line">log4j.appender.D.File = logs/jdbcTemplateHA_debug.log</div><div class="line">log4j.appender.D.Append = true</div><div class="line">log4j.appender.D.Threshold = DEBUG </div><div class="line">log4j.appender.D.layout = org.apache.log4j.PatternLayout</div><div class="line">log4j.appender.D.layout.ConversionPattern = %-d&#123;yyyy-MM-dd HH:mm:ss&#125;  [ %t:%r ] - [ %p ]  %m%n</div><div class="line"></div><div class="line">### 输出ERROR 级别以上的日志文件设置 ###</div><div class="line">log4j.appender.E = org.apache.log4j.DailyRollingFileAppender</div><div class="line">log4j.appender.E.File = logs/jdbcTemplateHA_error.log</div><div class="line">log4j.appender.E.Append = true</div><div class="line">log4j.appender.E.Threshold = ERROR </div><div class="line">log4j.appender.E.layout = org.apache.log4j.PatternLayout</div><div class="line">log4j.appender.E.layout.ConversionPattern = %-d&#123;yyyy-MM-dd HH:mm:ss&#125;  [ %t:%r ] - [ %p ]  %m%n</div></pre></td></tr></table></figure>
</li>
<li><p>添加spring数据源配置(spring-jdbc.xml) </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div></pre></td><td class="code"><pre><div class="line">&lt;bean id=&quot;statFilter&quot; class=&quot;com.alibaba.druid.filter.stat.StatFilter&quot;&gt;</div><div class="line">	&lt;property name=&quot;mergeSql&quot; value=&quot;true&quot; /&gt;</div><div class="line">	&lt;property name=&quot;slowSqlMillis&quot; value=&quot;3000&quot; /&gt;</div><div class="line">	&lt;property name=&quot;logSlowSql&quot; value=&quot;true&quot; /&gt;</div><div class="line">&lt;/bean&gt;</div><div class="line"></div><div class="line">&lt;!-- 使用druid连接池,并配置通用属性 --&gt;</div><div class="line">&lt;bean id=&quot;parentDataSource&quot; class=&quot;com.alibaba.druid.pool.DruidDataSource&quot; abstract=&quot;true&quot;&gt;</div><div class="line">	&lt;property name=&quot;initialSize&quot; value=&quot;5&quot;/&gt;</div><div class="line">	&lt;property name=&quot;minIdle&quot; value=&quot;5&quot;/&gt;</div><div class="line">	&lt;property name=&quot;maxActive&quot; value=&quot;100&quot;/&gt;</div><div class="line">	&lt;property name=&quot;maxWait&quot; value=&quot;30000&quot;/&gt;</div><div class="line">	&lt;property name=&quot;timeBetweenEvictionRunsMillis&quot; value=&quot;60000&quot; /&gt;</div><div class="line">	&lt;property name=&quot;minEvictableIdleTimeMillis&quot; value=&quot;300000&quot; /&gt;</div><div class="line">	&lt;property name=&quot;validationQuery&quot; value=&quot;select 1&quot;/&gt;</div><div class="line">	&lt;property name=&quot;testWhileIdle&quot; value=&quot;true&quot; /&gt;</div><div class="line">	&lt;property name=&quot;testOnBorrow&quot; value=&quot;false&quot; /&gt;</div><div class="line">	&lt;property name=&quot;testOnReturn&quot; value=&quot;false&quot; /&gt;</div><div class="line">	&lt;property name=&quot;poolPreparedStatements&quot; value=&quot;false&quot; /&gt;</div><div class="line">	&lt;property name=&quot;maxPoolPreparedStatementPerConnectionSize&quot; value=&quot;20&quot; /&gt;</div><div class="line">	&lt;!-- 超过时间限制是否回收 --&gt;  </div><div class="line">	&lt;property name=&quot;removeAbandoned&quot; value=&quot;true&quot;/&gt;  </div><div class="line">	&lt;!-- 超时时间；单位为秒。180秒=3分钟 --&gt;  </div><div class="line">	&lt;property name=&quot;removeAbandonedTimeout&quot; value=&quot;180&quot;/&gt;</div><div class="line">	&lt;!-- 关闭abanded连接时输出错误日志 --&gt;  </div><div class="line">	&lt;property name=&quot;logAbandoned&quot; value=&quot;false&quot; /&gt;</div><div class="line">	&lt;property name=&quot;proxyFilters&quot;&gt;</div><div class="line">		&lt;list&gt;</div><div class="line">			&lt;ref bean=&quot;statFilter&quot;&gt;&lt;/ref&gt;</div><div class="line">		&lt;/list&gt;</div><div class="line">	&lt;/property&gt;</div><div class="line">&lt;/bean&gt;</div><div class="line">&lt;!-- 配置主库(写库)数据源 --&gt;</div><div class="line">&lt;bean id=&quot;crmUpdateDataSource&quot; parent=&quot;parentDataSource&quot;&gt;</div><div class="line">	&lt;property name=&quot;url&quot;&gt;</div><div class="line">		&lt;value&gt;jdbc:mysql://$&#123;jdbc.crmupdate.database&#125;?useUnicode=true&amp;amp;characterEncoding=gbk&amp;amp;zeroDateTimeBehavior=convertToNull&lt;/value&gt;</div><div class="line">	&lt;/property&gt;</div><div class="line">    &lt;property name=&quot;username&quot; value=&quot;$&#123;jdbc.crmupdate.user&#125;&quot;/&gt;</div><div class="line">    &lt;property name=&quot;password&quot; value=&quot;$&#123;jdbc.crmupdate.password&#125;&quot;/&gt;</div><div class="line">&lt;/bean&gt;</div><div class="line"></div><div class="line">&lt;!-- 配置从库1数据源(读库) --&gt;</div><div class="line">&lt;bean id=&quot;crmQuery1DataSource&quot; parent=&quot;parentDataSource&quot;&gt;</div><div class="line">	&lt;property name=&quot;url&quot;&gt;</div><div class="line">		&lt;value&gt;jdbc:mysql://$&#123;jdbc.crmquery1.database&#125;?useUnicode=true&amp;amp;characterEncoding=gbk&amp;amp;zeroDateTimeBehavior=convertToNull&lt;/value&gt;</div><div class="line">	&lt;/property&gt;</div><div class="line">    &lt;property name=&quot;username&quot; value=&quot;$&#123;jdbc.crmquery1.user&#125;&quot;/&gt;</div><div class="line">    &lt;property name=&quot;password&quot; value=&quot;$&#123;jdbc.crmquery1.password&#125;&quot;/&gt;</div><div class="line">&lt;/bean&gt;</div><div class="line"></div><div class="line">&lt;!-- 配置从库2数据源(读库) --&gt;</div><div class="line">&lt;bean id=&quot;crmQuery2DataSource&quot; parent=&quot;parentDataSource&quot;&gt;</div><div class="line">	&lt;property name=&quot;url&quot;&gt;</div><div class="line">		&lt;value&gt;jdbc:mysql://$&#123;jdbc.crmquery2.database&#125;?useUnicode=true&amp;amp;characterEncoding=gbk&amp;amp;zeroDateTimeBehavior=convertToNull&lt;/value&gt;</div><div class="line">	&lt;/property&gt;</div><div class="line">    &lt;property name=&quot;username&quot; value=&quot;$&#123;jdbc.crmquery2.user&#125;&quot;/&gt;</div><div class="line">    &lt;property name=&quot;password&quot; value=&quot;$&#123;jdbc.crmquery2.password&#125;&quot;/&gt;</div><div class="line">&lt;/bean&gt;</div><div class="line"></div><div class="line">&lt;!-- 配置主库jdbcTemplate --&gt;</div><div class="line">&lt;bean id=&quot;crmUpdate&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;</div><div class="line">	&lt;property name=&quot;dataSource&quot; ref=&quot;crmUpdateDataSource&quot;/&gt;</div><div class="line">&lt;/bean&gt;</div><div class="line"></div><div class="line">&lt;!-- 配置从库1jdbcTemplate --&gt;</div><div class="line">&lt;bean id=&quot;crmQuery1&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;</div><div class="line">	&lt;property name=&quot;dataSource&quot; ref=&quot;crmQuery1DataSource&quot;/&gt;</div><div class="line">&lt;/bean&gt;</div><div class="line"></div><div class="line">&lt;!-- 配置从库2jdbcTemplate --&gt;</div><div class="line">&lt;bean id=&quot;crmQuery2&quot; class=&quot;org.springframework.jdbc.core.JdbcTemplate&quot;&gt;</div><div class="line">	&lt;property name=&quot;dataSource&quot; ref=&quot;crmQuery2DataSource&quot;/&gt;</div><div class="line">&lt;/bean&gt;</div></pre></td></tr></table></figure>
</li>
</ol>
<h5 id="三、编写实现查询HA的相关类"><a href="#三、编写实现查询HA的相关类" class="headerlink" title="三、编写实现查询HA的相关类"></a>三、编写实现查询HA的相关类</h5><img src="/typhoon/2017/09/17/jdbcTemplate实现HA/2.png" alt="result" title="result"> 
<pre><code>从图中可以看到,实现HA主要有上边标注的几个类,下边将逐个描述各个类的作用
</code></pre><ol>
<li><p>BalanceNodeBean<br> 该类是实现负载均衡的bean,代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * 负载均衡用的NodeBean</div><div class="line"> *</div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-09-17 13:58 Sunday</div><div class="line"> * @since V2.0</div><div class="line"> */</div><div class="line">public class BalanceNodeBean &#123;</div><div class="line">    /**</div><div class="line">     * Node Id节点id</div><div class="line">     */</div><div class="line">    private String nodeId = null;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * Node配置的权重，默认是100</div><div class="line">     */</div><div class="line">    private float weight = 100;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 权重修正系数-1.0 - +1.0</div><div class="line">     */</div><div class="line">    private float correctionWeight = 0;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 当前权重，运行时的动态权值</div><div class="line">     */</div><div class="line">    private float currentWeight = 0;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 最大失败次数</div><div class="line">     */</div><div class="line">    private int maxFails = 0;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 多长时间内出现max_fails次失败便认为后端down掉了</div><div class="line">     */</div><div class="line">    private int failTimeout = 0;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * Node的downFlag，默认是1</div><div class="line">     */</div><div class="line">    private int downFlag = 1;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * Node的backupFlag，默认是0</div><div class="line">     */</div><div class="line">    private int backupFlag = 0;</div><div class="line"></div><div class="line">   //为缩减篇幅,set和get方法省略</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>NodeHealthValueBean<br> 实现健康值检查的bean,代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * 负载均衡用的Node健康值Bean</div><div class="line"> *</div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-09-17 14:02 Sunday</div><div class="line"> * @since V2.0</div><div class="line"> */</div><div class="line">public class NodeHealthValueBean implements Serializable &#123;</div><div class="line">    private static final long serialVersionUID = 1L;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * Node index</div><div class="line">     */</div><div class="line">    private int nodeIndex = -1;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * Node健康值</div><div class="line">     */</div><div class="line">    private int healthValue = 0;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * Node健康值的最后更新时间</div><div class="line">     */</div><div class="line">    private Date lastUpdate = new Date();</div><div class="line"></div><div class="line">    //set和get方法省略</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ol>
<ol>
<li>MyLoadBalance<br>根据可用JdbcTemplate列表实现负载均衡访问的工具类,代码如下:</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * 负载均衡器</div><div class="line"> * (1)支持各节点间的负载均衡</div><div class="line"> * (2)支持每个节点的权重设定</div><div class="line"> * (3)支持单个节点的动态故障隔离和故障恢复</div><div class="line"> * (4)支持每个节点的动态权重修正系数设定</div><div class="line"> *</div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-09-17 18:39 Sunday</div><div class="line"> * @since V2.0</div><div class="line"> */</div><div class="line">public class MyLoadBalance &#123;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 取得 将使用的 BalanceNode index</div><div class="line">     *</div><div class="line">     * @param serverList serverList</div><div class="line">     * @return 将使用的 BalanceNode index</div><div class="line">     */</div><div class="line">    public static int getForwardServerIndex(</div><div class="line">            ArrayList&lt;BalanceNodeBean&gt; serverList) &#123;</div><div class="line">        // check para</div><div class="line">    	if(CollectionUtils.isEmpty(serverList)) &#123;</div><div class="line">    		return -1;</div><div class="line">    	&#125;</div><div class="line">    	int len = serverList.size();</div><div class="line">        int result = -1;</div><div class="line">        if (len == 1) &#123;</div><div class="line">            // (2)仅有一台server时</div><div class="line">            if (serverList.get(0).getDownFlag() == 1) &#123;</div><div class="line">                // 无可用的server</div><div class="line">                result = -1;</div><div class="line">            &#125; else &#123;</div><div class="line">                // 仅这一台</div><div class="line">                result = 0;</div><div class="line">            &#125;</div><div class="line">            return result;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        // (3)有多台后端服务器</div><div class="line">        BalanceNodeBean bestBean = null;</div><div class="line">        BalanceNodeBean tempBean = null;</div><div class="line"></div><div class="line">        float currentWeight = 0;</div><div class="line">        // 所有服务器总权重</div><div class="line">        float totalEffectiveWeight = 0;</div><div class="line">        // 遍历所有服务器, 按照各台服务器的当前权值进行选择</div><div class="line">        for (int i = 0; i &lt; len; i++) &#123;</div><div class="line">            tempBean = serverList.get(i);</div><div class="line"></div><div class="line">            if (tempBean.getDownFlag() == 1) &#123;</div><div class="line">                // Down掉的server,将被skip.</div><div class="line">                continue;</div><div class="line">            &#125;</div><div class="line"></div><div class="line">            // 计算当前权值，包含权重修正系数</div><div class="line">            currentWeight = tempBean.getCurrentWeight() + tempBean.getWeight()</div><div class="line">                    * (1 + tempBean.getCorrectionWeight());</div><div class="line">            tempBean.setCurrentWeight(currentWeight);</div><div class="line"></div><div class="line">            // 总的权重计算，包含权重修正系数</div><div class="line">            totalEffectiveWeight += tempBean.getWeight()</div><div class="line">                    * (1 + tempBean.getCorrectionWeight());</div><div class="line"></div><div class="line">            // 选择</div><div class="line">            if (bestBean == null</div><div class="line">                    || bestBean.getCurrentWeight() &lt; tempBean</div><div class="line">                    .getCurrentWeight()) &#123;</div><div class="line">                // 选择当前权重最大的serverNode</div><div class="line">                bestBean = tempBean;</div><div class="line">                //</div><div class="line">                result = i;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        if (bestBean == null) &#123;</div><div class="line">            // 无可用的server</div><div class="line">            return -1;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        if (bestBean != null) &#123;</div><div class="line">            // 该服务器这次被选中，因此要降低权值,以便下次计算。</div><div class="line">            currentWeight = bestBean.getCurrentWeight() - totalEffectiveWeight;</div><div class="line">            bestBean.setCurrentWeight(currentWeight);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        return result;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ol>
<li><p>HABalanceSimpleJdbcOperations<br> 和调用方直接打交道的类,实现了JdbcOperations接口,提供了和JdbcTemplate一样的功能(具体操作还是委托给具体的jdbcTemplate去完成),<br> 同时实现了PropertyChangeListener接口,对JdbcTemplate列表对应的健康值监听并完成健康值矫正操作.代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div><div class="line">150</div><div class="line">151</div><div class="line">152</div><div class="line">153</div><div class="line">154</div><div class="line">155</div><div class="line">156</div><div class="line">157</div><div class="line">158</div><div class="line">159</div><div class="line">160</div><div class="line">161</div><div class="line">162</div><div class="line">163</div><div class="line">164</div><div class="line">165</div><div class="line">166</div><div class="line">167</div><div class="line">168</div><div class="line">169</div><div class="line">170</div><div class="line">171</div><div class="line">172</div><div class="line">173</div><div class="line">174</div><div class="line">175</div><div class="line">176</div><div class="line">177</div><div class="line">178</div><div class="line">179</div><div class="line">180</div><div class="line">181</div><div class="line">182</div><div class="line">183</div><div class="line">184</div><div class="line">185</div><div class="line">186</div><div class="line">187</div><div class="line">188</div><div class="line">189</div><div class="line">190</div><div class="line">191</div><div class="line">192</div><div class="line">193</div><div class="line">194</div><div class="line">195</div><div class="line">196</div><div class="line">197</div><div class="line">198</div><div class="line">199</div><div class="line">200</div><div class="line">201</div><div class="line">202</div><div class="line">203</div><div class="line">204</div><div class="line">205</div><div class="line">206</div><div class="line">207</div><div class="line">208</div><div class="line">209</div><div class="line">210</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * 高可用jdbcOperations</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-09-17 13:54 Sunday</div><div class="line"> * @since V2.0</div><div class="line"> */</div><div class="line">public class HABalanceSimpleJdbcOperations implements PropertyChangeListener, JdbcOperations &#123;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * LOG</div><div class="line">     */</div><div class="line">	private static Logger log = Logger.getLogger(HABalanceSimpleJdbcOperations.class);</div><div class="line">   // private static org.slf4j.Logger log = LoggerFactory.getLogger(HABalanceSimpleJdbcOperations.class);</div><div class="line"></div><div class="line">    /**</div><div class="line">     * DB从库server列表</div><div class="line">     */</div><div class="line">    private ArrayList&lt;BalanceNodeBean&gt; serverList = new ArrayList&lt;BalanceNodeBean&gt;();</div><div class="line"></div><div class="line">    /**</div><div class="line">     * DB从库server列表用的readWriteLock</div><div class="line">     */</div><div class="line">    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();</div><div class="line">    /**</div><div class="line">     * 备机列表(查询库)</div><div class="line">     */</div><div class="line">    protected List&lt;JdbcOperations&gt; crmB_N_JdbcList;</div><div class="line">    /**</div><div class="line">     * 主机ip(写库)</div><div class="line">     */</div><div class="line">    protected JdbcOperations       crmJdbc;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 构造器</div><div class="line">     *</div><div class="line">     * @param crmB_N_JdbcList</div><div class="line">     */</div><div class="line">    public HABalanceSimpleJdbcOperations(</div><div class="line">            List&lt;JdbcOperations&gt; crmB_N_JdbcList,</div><div class="line">            JdbcOperations crmJdbc) &#123;</div><div class="line"></div><div class="line">        this.crmB_N_JdbcList = crmB_N_JdbcList;</div><div class="line">        this.crmJdbc = crmJdbc;</div><div class="line">        // 生成相应的serverList</div><div class="line">        int             len      = this.crmB_N_JdbcList.size();</div><div class="line">        BalanceNodeBean nodeBean = null;</div><div class="line">        for (int i = 0; i &lt; len; i++) &#123;</div><div class="line">            nodeBean = new BalanceNodeBean();</div><div class="line">            // 初始状态为正常</div><div class="line">            nodeBean.setDownFlag(0);</div><div class="line">            nodeBean.setCorrectionWeight(0);</div><div class="line">            nodeBean.setCurrentWeight(0);</div><div class="line">            // add</div><div class="line">            this.serverList.add(nodeBean);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        // Thread数</div><div class="line">        int threadNum = 1;</div><div class="line">        // 新建一个Threadpool</div><div class="line">        ExecutorService              threadPool = Executors.newFixedThreadPool(threadNum);</div><div class="line">        HABalanceJdbcHealthCheckTask task       = null;</div><div class="line">        for (int i = 0; i &lt; threadNum; i++) &#123;//使用threadNum个线程去监听jdbcTemplate列表的健康状态,</div><div class="line">		//如果出现健康值变动,触发监听器修改节点的健康状态</div><div class="line">            // 新作成一个Task</div><div class="line">            task = new HABalanceJdbcHealthCheckTask(this.crmB_N_JdbcList);</div><div class="line">            // add PropertyChangeListener</div><div class="line">            task.addPropertyChangeListener(this);</div><div class="line"></div><div class="line">            // 提交task到Threadpool</div><div class="line">            threadPool.execute(task);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * healthyValue属性改变通知处理。 根据healthyValue修改节点的DownFlag和权重修正系数。</div><div class="line">     */</div><div class="line">    public void propertyChange(PropertyChangeEvent event) &#123;</div><div class="line">        if (event.getPropertyName().equalsIgnoreCase(&quot;healthyValue&quot;)) &#123;</div><div class="line">            Object newBean = event.getNewValue();</div><div class="line">            if (newBean instanceof NodeHealthValueBean) &#123;</div><div class="line">                NodeHealthValueBean valueBean = (NodeHealthValueBean) newBean;</div><div class="line">                int                 nodeIndex = valueBean.getNodeIndex();</div><div class="line">                //</div><div class="line">                int healthValue = valueBean.getHealthValue();</div><div class="line"></div><div class="line">                if (healthValue &lt; 0) &#123;</div><div class="line">                    // 故障发生</div><div class="line">                    this.setNodeDownFlag(nodeIndex, 1);</div><div class="line">                &#125; else &#123;</div><div class="line">                    // 故障恢复</div><div class="line">                    this.setNodeDownFlag(nodeIndex, 0);</div><div class="line">                &#125;</div><div class="line"></div><div class="line">                // 权重修正系数</div><div class="line">                float correctionWeight = 0;</div><div class="line">                if (healthValue == 0) &#123;</div><div class="line">                    // 设置节点的权重修正系数为0</div><div class="line">                    correctionWeight = 0;</div><div class="line">                &#125; else if (healthValue == 1) &#123;</div><div class="line">                    // 设置节点的权重修正系数为 -0.1</div><div class="line">                    correctionWeight = -0.1f;</div><div class="line">                &#125; else if (healthValue == 2) &#123;</div><div class="line">                    // 设置节点的权重修正系数为 -0.3</div><div class="line">                    correctionWeight = -0.3f;</div><div class="line">                &#125; else if (healthValue == 3) &#123;</div><div class="line">                    // 设置节点的权重修正系数为 -0.5</div><div class="line">                    correctionWeight = -0.5f;</div><div class="line">                &#125; else if (healthValue == 4) &#123;</div><div class="line">                    // 设置节点的权重修正系数为 -1.0</div><div class="line">                    correctionWeight = -1.0f;</div><div class="line">                &#125;</div><div class="line">                // 设置节点的权重修正系数</div><div class="line">                this.setNodeCorrectionWeight(nodeIndex, correctionWeight);</div><div class="line"></div><div class="line">                // log</div><div class="line">                log.warn(&quot;nodeIndex=&quot; + nodeIndex + &quot;,healthValue=&quot;</div><div class="line">                                 + healthValue + &quot;,correctionWeight=&quot; + correctionWeight);</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 设置节点的downFlag</div><div class="line">     *</div><div class="line">     * @param nodeIndex</div><div class="line">     * @param downFlag</div><div class="line">     */</div><div class="line">    public void setNodeDownFlag(int nodeIndex, int downFlag) &#123;</div><div class="line">        // check para</div><div class="line">        if (nodeIndex &lt; 0 || nodeIndex &gt;= this.serverList.size()) &#123;</div><div class="line">            return;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        Lock writeLock = this.readWriteLock.writeLock();</div><div class="line">        //</div><div class="line">        writeLock.lock();</div><div class="line">        try &#123;</div><div class="line">            BalanceNodeBean nodeBean = this.serverList.get(nodeIndex);</div><div class="line">            // set downFlag</div><div class="line">            nodeBean.setDownFlag(downFlag);</div><div class="line">        &#125; finally &#123;</div><div class="line">            writeLock.unlock();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 设置节点的权重修正系数</div><div class="line">     *</div><div class="line">     * @param nodeIndex</div><div class="line">     * @param downFlag</div><div class="line">     */</div><div class="line">    public void setNodeCorrectionWeight(int nodeIndex, float correctionWeight) &#123;</div><div class="line">        // check para</div><div class="line">        if (nodeIndex &lt; 0 || nodeIndex &gt;= this.serverList.size()) &#123;</div><div class="line">            return;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        Lock writeLock = this.readWriteLock.writeLock();</div><div class="line">        //</div><div class="line">        writeLock.lock();</div><div class="line">        try &#123;</div><div class="line">            BalanceNodeBean nodeBean = this.serverList.get(nodeIndex);</div><div class="line">            // set correctionWeight</div><div class="line">            nodeBean.setCorrectionWeight(correctionWeight);</div><div class="line">        &#125; finally &#123;</div><div class="line">            writeLock.unlock();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    /**</div><div class="line">     * 使用负载均衡器取得一个可用JdbcOperations。</div><div class="line">     *</div><div class="line">     * @return</div><div class="line">     */</div><div class="line">    protected JdbcOperations getJdbcOperations() &#123;</div><div class="line">        JdbcOperations result      = null;</div><div class="line">        int            resultIndex = -1;</div><div class="line"></div><div class="line">        Lock readLock = this.readWriteLock.readLock();</div><div class="line">        // lock</div><div class="line">        readLock.lock();</div><div class="line">        try &#123;</div><div class="line">            // 取得一个server index</div><div class="line">            resultIndex = MyLoadBalance.getForwardServerIndex(this.serverList);</div><div class="line">            //log.warn(&quot;resultIndex=&quot; + resultIndex);</div><div class="line">        &#125; finally &#123;</div><div class="line">            // unlock</div><div class="line">            readLock.unlock();</div><div class="line">        &#125;</div><div class="line">        log.info(&quot;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;获取的负载均衡jdbcOperations节点resultIndex:&quot;+ resultIndex);</div><div class="line">        if (resultIndex &gt;= 0) &#123;</div><div class="line">            result = this.crmB_N_JdbcList.get(resultIndex);</div><div class="line">        &#125;</div><div class="line">        return result;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    @Override</div><div class="line">    public &lt;T&gt; List&lt;T&gt; query(String sql, RowMapper&lt;T&gt; rowMapper)</div><div class="line">            throws DataAccessException &#123;</div><div class="line">    	JdbcOperations jdbcOperation = getJdbcOperations();</div><div class="line">    	//log.debug(&quot;当前jdbc信息:&#123;&#125;&quot;,ToStringBuilder.reflectionToString(jdbcOperation));</div><div class="line">        return jdbcOperation.query(sql, rowMapper);</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    @Override</div><div class="line">    public int update(String sql) throws DataAccessException &#123;</div><div class="line">        return crmJdbc.update(sql);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>  由于实现了JdbcOperations接口,其定义的所有方法都要实现,此处忽略;另外可以观察到所有的读操作都是操作从库,<br>  写操作直接指定主库,从而实现了读写分离的操作.</p>
</li>
<li><p>HABalanceJdbcHealthCheckTask<br>该类实现了Runnable接口,可以独立运行,其作用是监听从库相关jdbcTemplate列表的健康值,如果有变化或者某个从库挂掉<br>会通知其监听器修改jdbcTemplate节点的健康值,代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div><div class="line">150</div><div class="line">151</div><div class="line">152</div><div class="line">153</div><div class="line">154</div><div class="line">155</div><div class="line">156</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * 高可用DB从库HealthCheck Task</div><div class="line"> *</div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-09-17 14:04 Sunday</div><div class="line"> * @since V2.0</div><div class="line"> */</div><div class="line">public class HABalanceJdbcHealthCheckTask implements Runnable &#123;</div><div class="line">/**</div><div class="line"> * LOG</div><div class="line"> */</div><div class="line">private static Logger log = Logger.getLogger(HABalanceJdbcHealthCheckTask.class);</div><div class="line"></div><div class="line">/**</div><div class="line"> * DB从库Jdbc列表</div><div class="line"> */</div><div class="line">private List&lt;JdbcOperations&gt; crmB_N_JdbcList;</div><div class="line"></div><div class="line">/**</div><div class="line"> * Node健康值Bean列表</div><div class="line"> */</div><div class="line">private ArrayList&lt;NodeHealthValueBean&gt; healthyValueList = new ArrayList&lt;NodeHealthValueBean&gt;();</div><div class="line"></div><div class="line">/**</div><div class="line"> * 运行中标志</div><div class="line"> */</div><div class="line">private volatile boolean runFlag = true;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 健康值 PropertyChangeSupport</div><div class="line"> */</div><div class="line">protected PropertyChangeSupport listeners = new PropertyChangeSupport(this);</div><div class="line"></div><div class="line">public HABalanceJdbcHealthCheckTask(List&lt;JdbcOperations&gt; crmB_N_JdbcList) &#123;</div><div class="line">	// DB从库Jdbc列表</div><div class="line">	this.crmB_N_JdbcList = crmB_N_JdbcList;</div><div class="line"></div><div class="line">	int len = this.crmB_N_JdbcList.size();</div><div class="line">	NodeHealthValueBean nodeBean = null;</div><div class="line">	for (int i = 0; i &lt; len; i++) &#123;</div><div class="line">		nodeBean = new NodeHealthValueBean();</div><div class="line">		nodeBean.setNodeIndex(i);</div><div class="line">		// 初始状态为正常</div><div class="line">		nodeBean.setHealthValue(0);</div><div class="line">		// add</div><div class="line">		this.healthyValueList.add(nodeBean);</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 添加 健康值PropertyChangeListener</div><div class="line"> *</div><div class="line"> * @param listener</div><div class="line"> */</div><div class="line">public void addPropertyChangeListener(PropertyChangeListener listener) &#123;</div><div class="line">	this.listeners.addPropertyChangeListener(listener);</div><div class="line">&#125;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 移除 健康值PropertyChangeListener</div><div class="line"> *</div><div class="line"> * @param listener</div><div class="line"> */</div><div class="line">public void removePropertyChangeListener(PropertyChangeListener listener) &#123;</div><div class="line">	this.listeners.removePropertyChangeListener(listener);</div><div class="line">&#125;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 取得健康值</div><div class="line"> *</div><div class="line"> * @param jdbcOpers</div><div class="line"> * @return -1: 表示已经Down; 0-4级;</div><div class="line"> */</div><div class="line">private int getHealthyValue(JdbcOperations jdbcOpers) &#123;</div><div class="line">	int result = 0;</div><div class="line">	try &#123;</div><div class="line">		long beforeMS = System.currentTimeMillis();</div><div class="line">		// query 主要用来做DB存活性以及性能探测</div><div class="line">		jdbcOpers.queryForObject(&quot;select 1 from dual&quot;, Integer.class);</div><div class="line">		long afterMS = System.currentTimeMillis();</div><div class="line"></div><div class="line">		// diff</div><div class="line">		long diff = afterMS - beforeMS;</div><div class="line"></div><div class="line">		// log</div><div class="line">		// log.warn(&quot;diff=&quot; + diff);</div><div class="line">		if (diff &gt;= 0 &amp;&amp; diff &lt;= 500) &#123;// 小于500毫秒为0级</div><div class="line">			// 执行时长0-500ms内为正常</div><div class="line">			result = 0;</div><div class="line">		&#125; else if (diff &gt; 500 &amp;&amp; diff &lt;= 1000) &#123;// 500毫秒到1秒之间是1级</div><div class="line">			// 执行时长500-1000ms内为降1级</div><div class="line">			result = 1;</div><div class="line">		&#125; else if (diff &gt; 1000 &amp;&amp; diff &lt;= 3000) &#123;// 1秒到3秒之间是2级</div><div class="line">			result = 2;</div><div class="line">		&#125; else if (diff &gt; 3000 &amp;&amp; diff &lt;= 5000) &#123;// 3秒到5秒之间是3级</div><div class="line">			result = 3;</div><div class="line">		&#125; else if (diff &gt; 5000) &#123;// 大于5秒是4级</div><div class="line">			result = 4;</div><div class="line">		&#125;</div><div class="line">	&#125; catch (Exception e) &#123;// 如果出现异常,认为DB挂掉</div><div class="line">		result = -1;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	return result;</div><div class="line">&#125;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 检测所有Node的健康值(5秒钟检查一下 )</div><div class="line"> */</div><div class="line">public void run() &#123;</div><div class="line">while (this.runFlag) &#123;</div><div class="line">	try &#123;</div><div class="line">		int len = this.crmB_N_JdbcList.size();</div><div class="line">		JdbcOperations jdbcOpers = null;</div><div class="line">		NodeHealthValueBean nodeBean = null;</div><div class="line">		int healthyValue = -1;</div><div class="line">		for (int i = 0; i &lt; len; i++) &#123;</div><div class="line">			jdbcOpers = this.crmB_N_JdbcList.get(i);</div><div class="line">			//</div><div class="line">			healthyValue = getHealthyValue(jdbcOpers);// 获得jdbc节点健康值</div><div class="line">			nodeBean = this.healthyValueList.get(i);// 健康节点</div><div class="line">			if (nodeBean.getHealthValue() == healthyValue) &#123;// 上一次节点健康值和当前健康值一致,不需要变动</div><div class="line">				continue;</div><div class="line">			&#125;</div><div class="line">			//节点健康值有变化</div><div class="line">			NodeHealthValueBean oldValue = new NodeHealthValueBean();//节点旧健康值</div><div class="line">			oldValue.setNodeIndex(i);</div><div class="line">			oldValue.setHealthValue(nodeBean.getHealthValue());</div><div class="line"></div><div class="line">			NodeHealthValueBean newValue = new NodeHealthValueBean();//节点新健康值</div><div class="line">			newValue.setNodeIndex(i);</div><div class="line">			newValue.setHealthValue(healthyValue);</div><div class="line"></div><div class="line">			PropertyChangeEvent event = new PropertyChangeEvent(this, &quot;healthyValue&quot;, oldValue, newValue);</div><div class="line">			// fire 健康值变化event</div><div class="line">			this.listeners.firePropertyChange(event);//触发监听器操作</div><div class="line"></div><div class="line">			// set new healthvalue</div><div class="line">			nodeBean.setHealthValue(healthyValue);//设置节点的新健康值</div><div class="line">			// set lastUpdate</div><div class="line">			nodeBean.setLastUpdate(new Date());</div><div class="line">		&#125;</div><div class="line">	&#125; catch (Exception e) &#123;</div><div class="line">		log.warn(e.getMessage());</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	try &#123;</div><div class="line">		// sleep 5 秒</div><div class="line">		Thread.sleep(5000);</div><div class="line">	&#125; catch (Exception e) &#123;</div><div class="line">		log.error(&quot;exception&quot;,e);</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以看到该类定义了监听管理器,再run方法中5秒执行一次jdbcTemplate节点健康性检查,如果发现当前健康值和节点之前健康值不一致,<br>会触发监听器通知其修改节点健康值属性</p>
</li>
</ol>
<h5 id="四、添加HA相关配置"><a href="#四、添加HA相关配置" class="headerlink" title="四、添加HA相关配置"></a>四、添加HA相关配置</h5><pre><code>在spring-jdbc.xml中添加如下配置
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&lt;!-- 注册ha jdbcTemplate --&gt;</div><div class="line">&lt;bean id=&quot;crmBalanceJdbc&quot; class=&quot;com.typhoon.jdbcTemplateHA.dao.ha.HABalanceSimpleJdbcOperations&quot;&gt;</div><div class="line">	&lt;constructor-arg index=&quot;0&quot;&gt;</div><div class="line">        &lt;list&gt;</div><div class="line">            &lt;ref  bean=&quot;crmQuery1&quot;/&gt;</div><div class="line">            &lt;ref  bean=&quot;crmQuery2&quot;/&gt;</div><div class="line">        &lt;/list&gt;         </div><div class="line">     &lt;/constructor-arg&gt;</div><div class="line">     &lt;constructor-arg index=&quot;1&quot; ref=&quot;crmUpdate&quot;/&gt;</div><div class="line">&lt;/bean&gt;</div></pre></td></tr></table></figure>
<pre><code>该案例中我们忽略更新操作;在HABalanceSimpleJdbcOperations构造器中根据jdbcTemplate列表构造出对应的用于实现负载均衡的BalanceNodeBean列表
(默认节点不是挂掉,当前权重0,矫正权重0),然后由一个线程池创建指定数量的线程是监视检查jdbcTemplate节点的健康情况,并且为每一个task添加
监视器(实现任何一个监视线程监测到jdbcTemplate健康值有变化,就会通知监听器修改健康值),为了不增加过多类和逻辑,HABalanceSimpleJdbcOperations也是
task的监听类(触发逻辑propertyChange)
</code></pre><h5 id="五、测试"><a href="#五、测试" class="headerlink" title="五、测试"></a>五、测试</h5><pre><code>HA功能和配置都写好了,接着我们需要些代码来验证
</code></pre><ol>
<li><p>两个从库中test库添加user表并插入两条记录<br> 从库1:</p>
<img src="/typhoon/2017/09/17/jdbcTemplate实现HA/3.png" alt="result" title="result"> 
<p> 从库2:</p>
<img src="/typhoon/2017/09/17/jdbcTemplate实现HA/4.png" alt="result" title="result"> 
<p> 两台机器上的test库中都有user表,有两条相同的记录</p>
</li>
</ol>
<ol>
<li><p>编写业务类<br>接口:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">public interface UserService &#123;</div><div class="line"></div><div class="line">	List&lt;User&gt; selectAll();</div><div class="line">	</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>接口默认实现:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">@Service(&quot;userService&quot;)</div><div class="line">public class UserServiceImpl implements UserService &#123;</div><div class="line"></div><div class="line">@Resource</div><div class="line">UserDao userDao;</div><div class="line"></div><div class="line">@Override</div><div class="line">public List&lt;User&gt; selectAll() &#123;</div><div class="line">	return this.userDao.selectAll();</div><div class="line">&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>数据交互dao操作类:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">    /**</div><div class="line"> * 用户信息操作dao</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> *</div><div class="line"> */</div><div class="line">@Repository(&quot;userDao&quot;)</div><div class="line">public class UserDao &#123;</div><div class="line"></div><div class="line">@Resource</div><div class="line">JdbcOperations crmBalanceJdbc;</div><div class="line"></div><div class="line">public List&lt;User&gt; selectAll() &#123;</div><div class="line">	String sql = &quot;		select * from user	&quot;;</div><div class="line">	return this.crmBalanceJdbc.query(sql, BeanPropertyRowMapper.newInstance(User.class));</div><div class="line">&#125;</div><div class="line">	</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>可以看到UserDao中的JdbcTemplate已经不是之前用到的了,而是我们自己定义的类型HABalanceSimpleJdbcOperations,<br>然后注入后就可以像其他JdbcTemplate或者NamedJdbcTemplate一样操作数据库了.</p>
</li>
<li><p>编写单元测试类<br>使用main方法借助SpringContextUtils来实现单元测试,代码如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">public class HAJdbcConsumer &#123;</div><div class="line"></div><div class="line">public static void main(String[] args) &#123;</div><div class="line">	new ClassPathXmlApplicationContext(&quot;spring-root.xml&quot;).start();</div><div class="line"></div><div class="line">	UserService userService = SpringContextUtil.getBean(&quot;userService&quot;, UserService.class);</div><div class="line">	List&lt;User&gt; list = null;</div><div class="line">	for (int i = 0; i &lt; 10; i++) &#123;</div><div class="line">		list = userService.selectAll();</div><div class="line">		System.out.println(JSON.toJSONString(list));</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如上述代码所示,我们获取userService后,执行了十次查询,然后我们运行程序得到如下结果:</p>
<img src="/typhoon/2017/09/17/jdbcTemplate实现HA/5.png" alt="result" title="result"> 
<p>细心的人发现了,我们确实查询到了我们想要的结果,但是完全看不出来十次查询分别是从哪个jdbcTemplate节点查询的,<br>很好办,刚开始我们定义的日志就派上用场了,我们查看获取jdbcTemplate节点的代码:</p>
<img src="/typhoon/2017/09/17/jdbcTemplate实现HA/6.png" alt="result" title="result">    
<p>在根据权重规则获取到权重最高的jdbcTemplate节点的时候会计算处其所在列表的索引,我们在计算出所有后使用日志打印索引的值,<br>也就是jdbcTemplate对应的节点索引值,如红色标注部分,接着我们再次运行单元测试,可以看到如下结果:</p>
<img src="/typhoon/2017/09/17/jdbcTemplate实现HA/7.png" alt="result" title="result">    
<p>可以看到我们每次查询操作都打印出了获取到的jdbcTempalte索引值,这样我们就基于spring-jdbc中的jdbcTemplate简单实现了HA</p>
</li>
</ol>
<h5 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h5><pre><code>当然此例只是简单的实现了HA和负载均衡,具体的业务场景中可能需要更加强大完善和性能比较好的实现方式,目前市面上比较流行的
有mycat,sharding-jdbc,atlas等一系列,各有千秋,不同公司要根据不同的业务场景进行技术选型或者自己团队实现.
</code></pre><p><em>PS</em>:希望我的总结能够给你带来一些改变和提升,荣幸至极!    </p>
  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/typhoon/categories/spring/">spring</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/typhoon/tags/jdbcTemplate高可用/">jdbcTemplate高可用</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://scorpioaeolus.oschina.io/2017/09/17/jdbcTemplate实现HA/" data-title="jdbcTemplate实现HA | Typhoon&#39;s code space" data-tsina="null" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/typhoon/2017/12/21/徒手搭建dubbo服务/" title="徒手搭建dubbo服务">
  <strong>上一篇：</strong><br/>
  <span>
  徒手搭建dubbo服务</span>
</a>
</div>


<div class="next">
<a href="/typhoon/2017/09/17/PropertyChangeListener概念和用法/"  title="PropertyChangeListener概念和用法">
 <strong>下一篇：</strong><br/> 
 <span>PropertyChangeListener概念和用法
</span>
</a>
</div>

</nav>

	


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#一、创建maven项目并添加最简依赖"><span class="toc-number">1.</span> <span class="toc-text">一、创建maven项目并添加最简依赖</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#二、添加配置文件"><span class="toc-number">2.</span> <span class="toc-text">二、添加配置文件</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#三、编写实现查询HA的相关类"><span class="toc-number">3.</span> <span class="toc-text">三、编写实现查询HA的相关类</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#四、添加HA相关配置"><span class="toc-number">4.</span> <span class="toc-text">四、添加HA相关配置</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#五、测试"><span class="toc-number">5.</span> <span class="toc-text">五、测试</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#总结"><span class="toc-number">6.</span> <span class="toc-text">总结</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/typhoon/categories/dubbo/" title="dubbo">dubbo<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java性能优化/" title="java性能优化">java性能优化<sup>17</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java源码分析/" title="java源码分析">java源码分析<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/motan/" title="motan">motan<sup>2</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/spring/" title="spring">spring<sup>11</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springboot/" title="springboot">springboot<sup>28</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springmvc/" title="springmvc">springmvc<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/容器/" title="容器">容器<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/工具/" title="工具">工具<sup>7</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/性能优化/" title="性能优化">性能优化<sup>5</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/架构/" title="架构">架构<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/案例分析/" title="案例分析">案例分析<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/缓存/" title="缓存">缓存<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/面试题/" title="面试题">面试题<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">Tags</p>
		<ul class="clearfix">
		
			
				<li><a href="/typhoon/tags/springboot/" title="springboot">springboot<sup>28</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/java性能优化/" title="java性能优化">java性能优化<sup>9</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/限流/" title="限流">限流<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring5/" title="Spring5">Spring5<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/案例分析/" title="案例分析">案例分析<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/性能优化/" title="性能优化">性能优化<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring/" title="Spring">Spring<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo/" title="dubbo">dubbo<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/分页/" title="分页">分页<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/并发/" title="并发">并发<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/异常拦截/" title="异常拦截">异常拦截<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo分布式事务/" title="dubbo分布式事务">dubbo分布式事务<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/自带图片/" title="自带图片">自带图片<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/svn导出mvn项目/" title="svn导出mvn项目">svn导出mvn项目<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo过滤器/" title="dubbo过滤器">dubbo过滤器<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/排序性能对比/" title="排序性能对比">排序性能对比<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/ListenableFuture/" title="ListenableFuture">ListenableFuture<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/PropertyChangeListener/" title="PropertyChangeListener">PropertyChangeListener<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/jdbcTemplate高可用/" title="jdbcTemplate高可用">jdbcTemplate高可用<sup>1</sup></a></li>
			
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=b3593ceb&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m a java coder. <br/>
			This is my blog,believe it or not.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
		<a href="mailto:ScorpioAeolus@163.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2019 
		
		<a href="/typhoon/about" target="_blank" title="typhoon">typhoon</a>
		
		
		</p>
</div>
</footer>
    <script src="/typhoon/js/jquery-2.0.3.min.js"></script>
<script src="/typhoon/js/jquery.imagesloaded.min.js"></script>
<script src="/typhoon/js/gallery.js"></script>
<script src="/typhoon/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>









<link rel="stylesheet" href="/typhoon/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/typhoon/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/typhoon/img/scrollup.png"/></a>
	</div>
	<script src="/typhoon/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
